<?php

require_once( ORM_DIR.'/StoredObjectDescriptor.php' );

/**
 * Хранимый объект
 * 
 * @author alno
 */
class StoredObject {
	
	private $_descriptor;
	
	private $_fields;
	
	private $_storage;
	
	public function __construct( StoredObjectDescriptor & $descriptor ) {
		$this->_descriptor = & $descriptor;
		$this->_fields = array();
		
		$descFields = $this->_descriptor->getFields();
		
		foreach ( $descFields as $fieldName => $fieldDesc ) {
			$this->_fields[ $fieldName ] = null;
		}
	}
	
	public function __get( $name ) {
		$extractors = $this->_descriptor->getExtractors();
		
		if ( isset( $extractors[ $name ] ) ) {
			return $extractors[ $name ]->get( $this->_storage, $this->_fields );
		} else {
			return false;
		}
	}
	
	public function __set( $name, $value ) {
		$extractors = $this->_descriptor->getExtractors();
		
		if ( isset( $extractors[ $name ] ) ) {
			$extractors[ $name ]->set( $this->_storage, $this->_fields, $value );
		} else {
			return false;
		}
	}
	
	public function setStorage( Storage & $storage ) {
		$this->_storage = & $storage;
	}
	
	public function & getDescriptor() {
		return $this->_descriptor;
	}
	
	public function & getFields() {
		return $this->_fields;
	}
	
	public function getPrimaryKey() {
		return $this->_fields[ $this->_descriptor->getPrimaryKeyName() ];
	}
	
	public function setPrimaryKey( $primaryKeyValue ) {
		$this->_fields[ $this->_descriptor->getPrimaryKeyName() ] = $primaryKeyValue;
	}

	/**
	 * Загрузить объект из карты свойств
	 *
	 * @param array $data карта свойств
	 */
	public function mergeFields( $data ) {
		foreach( $this->_fields as $fieldName => $oldFieldValue ) if ( isset( $data[ $fieldName ] ) ) {
			$this->_fields[ $fieldName ] = $data[ $fieldName ];
		}
	}
}

?>